package com.ytd.smartcanteen.weighting.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ytd.common.bean.LocalServerSetting;
import com.ytd.common.util.DeviceUtil;
import com.ytd.common.util.ReadFileUtil;
import com.ytd.common.util.ThreadUtil;
import com.ytd.common.util.YtdConfig;
import com.ytd.smartcanteen.weighting.MainActivity;

import java.util.ArrayList;
import java.util.List;

import cn.ytd.smartcanteen.weighting.R;

public class BindDialog extends BaseDialog {
    private TextView btnOK2;
    MainActivity mActivity;
    EditText edit_IP, edit_Port;
    TextView txt_row, txt_column, txt_name;
    TextView btnOK, btnBack;
    View view_fj;
    LinearLayout lin_set, lin_zw;
    List<String> row_buf = new ArrayList<>();
    List<String> column_buf = new ArrayList<>();
    int row_num = 1, column_num = 1, checkNum = 1, typrNum = 1;
    boolean isReconnection = false;
    private View mMenuView;
    private TextView txtTitle;
    private ListView chooseIteam;
    private ChooseListAdapter chooselist;
    private boolean executeCheckServerSetting = false;

    @SuppressLint({"InflateParams", "SetTextI18n"})
    public BindDialog(MainActivity context) {
        super(context);
        mActivity = context;
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.dialog_bind, null);
        initView();
        initData();
        initListener();
        this.setBackgroundDrawable(new BitmapDrawable());
        this.setContentView(mMenuView);
        this.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        int h = context.getWindowManager().getDefaultDisplay().getHeight();
        this.setHeight(h - 50);
        this.setFocusable(true);
        this.setOutsideTouchable(false);
        this.setAnimationStyle(R.style.DialogShow);
    }

    private void initListener() {
        mMenuView.findViewById(R.id.ll_bind_row).setOnClickListener(v -> {
            lin_zw.setVisibility(View.GONE);
            lin_set.setVisibility(View.VISIBLE);
            view_fj.setVisibility(View.VISIBLE);
            typrNum = 1;
            txtTitle.setText(mActivity.getString(R.string.text_please_select));
            checkNum = row_num;
            chooselist.clear();
            for (int i = 0; i < row_buf.size(); i++) {
                if (i + 1 != checkNum) {
                    chooselist.addIteam(new ChooseItem(row_buf.get(i), false));
                } else {
                    chooselist.addIteam(new ChooseItem(row_buf.get(i), true));
                }

            }
            chooseIteam.setAdapter(chooselist);
        });
        mMenuView.findViewById(R.id.ll_bind_column).setOnClickListener(v -> {
            lin_zw.setVisibility(View.GONE);
            lin_set.setVisibility(View.VISIBLE);
            view_fj.setVisibility(View.VISIBLE);
            chooselist.clear();
            typrNum = 0;
            checkNum = column_num;
            txtTitle.setText(mActivity.getString(R.string.text_please_select));
            for (int i = 0; i < column_buf.size(); i++) {
                if (i + 1 != checkNum) {
                    chooselist.addIteam(new ChooseItem(column_buf.get(i), false));
                } else {
                    chooselist.addIteam(new ChooseItem(column_buf.get(i), true));
                }

            }
            chooseIteam.setAdapter(chooselist);
        });
        btnBack.setOnClickListener(v -> {
            if (lin_zw.getVisibility() == View.GONE) {
                lin_zw.setVisibility(View.VISIBLE);
                lin_set.setVisibility(View.GONE);
                view_fj.setVisibility(View.GONE);
            } else {
                dismiss();
            }
        });
        btnOK.setOnClickListener(v -> {
            if (lin_set.getVisibility() == View.VISIBLE) {
                btnOK2.performClick();
            }
            isReconnection = false;
            if (!edit_IP.getText().toString().equals(YtdConfig.getIP())) {
                isReconnection = true;
                YtdConfig.setIP(edit_IP.getText().toString().trim());
            }
            if (Integer.valueOf(edit_Port.getText().toString()) != YtdConfig.getPort()) {
                isReconnection = true;
                YtdConfig.setPort(Integer.valueOf(edit_Port.getText().toString()));
            }

            YtdConfig.setRow(row_num);
            YtdConfig.setColumn(column_num);
            context.saveConfig(isReconnection);
            ReadFileUtil.delServerSettingFile();
            dismiss();
        });
        btnOK2.setOnClickListener(v -> {
            //销毁弹出框
            lin_zw.setVisibility(View.VISIBLE);
            lin_set.setVisibility(View.GONE);
            view_fj.setVisibility(View.GONE);
            CheckResult(checkNum, typrNum);
        });
    }

    @Override
    public void dismiss() {
        executeCheckServerSetting = false;
        super.dismiss();
    }

    private void initData() {
        chooselist = new ChooseListAdapter(context);
        chooseIteam.setOnItemClickListener(new ChooseItemClick());
        chooseIteam.setAdapter(chooselist);
        initRowColumn();
        if (!YtdConfig.isDeviceActivate()) {
            context.setTitle("设备激活");
            checkServerSetting();
        } else {
            context.setTitle("设备配置");
        }
        row_num = YtdConfig.getRow();
        column_num = YtdConfig.getColumn();

        edit_IP.setText(YtdConfig.getIP());
        edit_Port.setText(YtdConfig.getPort() + "");
        txt_row.setText(row_num + "");
        txt_column.setText(column_num + "");

    }

    private void checkServerSetting() {
        executeCheckServerSetting = true;
        ThreadUtil.execute(() -> {
            while (executeCheckServerSetting) {
                LocalServerSetting localServerSetting = ReadFileUtil.readServerSetting();
                if (localServerSetting != null) {
                    executeCheckServerSetting = false;
                    edit_IP.post(() -> {
                        edit_IP.setText(localServerSetting.serverIp);
                        edit_Port.setText(localServerSetting.serverPort);
                    });
                }
                SystemClock.sleep(1000);
            }
        });
    }

    private void initView() {
        edit_IP = mMenuView.findViewById(R.id.edit_bind_ip);
        edit_Port = mMenuView.findViewById(R.id.edit_bind_port);
        txt_row = mMenuView.findViewById(R.id.txt_bind_row);
        txt_column = mMenuView.findViewById(R.id.txt_bind_column);
        btnOK = mMenuView.findViewById(R.id.btn_bind_ok);
        txt_name = mMenuView.findViewById(R.id.txt_bind_name);
        view_fj = mMenuView.findViewById(R.id.view_fj);
        lin_set = mMenuView.findViewById(R.id.lin_set);
        lin_zw = mMenuView.findViewById(R.id.lin_zw);
        btnBack = mMenuView.findViewById(R.id.set_btn_back);
        chooseIteam = mMenuView.findViewById(R.id.choose_list);
        txtTitle = mMenuView.findViewById(R.id.choose_txt);
        btnOK2 = mMenuView.findViewById(R.id.choose_determine);
        mMenuView.findViewById(R.id.lin_zw).setOnLongClickListener(v -> {
            Toast.makeText(mMenuView.getContext(), DeviceUtil.getDeviceSN(), Toast.LENGTH_LONG).show();
            return false;
        });
    }

    private void initRowColumn() {
        int maxRow = 9;
        for (int i = 1; i <= maxRow; i++) {
            row_buf.add(String.valueOf(i));
        }
        int maxColumn = 20;
        for (int i = 1; i <= maxColumn; i++) {
            column_buf.add(String.valueOf(i));
        }
    }

    public void Show(int gravity, int x, int y) {
        showAtLocation(mMenuView, gravity, x, y);
    }

    public void CheckResult(int Num, int Type) {
        if (Type == 1) {
            row_num = Num;
            txt_row.setText("" + Num);
        } else {
            column_num = Num;
            txt_column.setText("" + Num);
        }

    }

    static class ViewHolder {
        TextView chooseName;
        ImageView chooseImg;
    }

    private class ChooseItemClick implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            chooselist.updateItem(checkNum - 1, false);
            checkNum = position + 1;
            chooselist.updateItem(position, true);
            chooselist.notifyDataSetChanged();
        }
    }

    private class ChooseListAdapter extends BaseAdapter {
        private ArrayList<ChooseItem> mLeIteam = new ArrayList<>();
        private LayoutInflater mInflator;

        public ChooseListAdapter(Activity activity) {
            super();
            mLeIteam = new ArrayList<ChooseItem>();
            mInflator = activity.getLayoutInflater();
        }

        public void addIteam(ChooseItem iteam) {
            if (!mLeIteam.contains(iteam)) {
                mLeIteam.add(iteam);
            }
        }

        public ChooseItem getIteam(int position) {
            return mLeIteam.get(position);
        }

        public void clear() {
            mLeIteam.clear();
        }

        @Override
        public int getCount() {
            return mLeIteam.size();
        }

        @Override
        public Object getItem(int i) {
            return mLeIteam.get(i);
        }

        public void updateItem(int i, Boolean value) {
            if (i >= 0 && i < mLeIteam.size()) {
                mLeIteam.get(i).setCheck(value);
            }
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            final int iteamID = i;
            // 一般列表视图的优化代码。
            if (view == null) {
                view = mInflator.inflate(R.layout.list_choose, null);
                viewHolder = new ViewHolder();
                viewHolder.chooseName = view.findViewById(R.id.choose_name);
                viewHolder.chooseImg = view.findViewById(R.id.choose_img);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }
            ChooseItem Litem = mLeIteam.get(i);
            viewHolder.chooseName.setText(Litem.getName());
            if (Litem.getCheck()) {
                viewHolder.chooseImg.setVisibility(View.VISIBLE);
            } else {
                viewHolder.chooseImg.setVisibility(View.GONE);
            }
            return view;
        }

    }

    public class ChooseItem {
        String name;
        Boolean isCheck;

        public ChooseItem(String Name, Boolean IsCheck) {
            name = Name;
            isCheck = IsCheck;
        }

        public String getName() {
            return name;
        }

        public Boolean getCheck() {
            return isCheck;
        }

        public void setCheck(Boolean check) {
            isCheck = check;
        }

    }
}
